$(function(){

	$('#selectShip').click(function(){
		
		initShipTable();
		
		$('#modalShip').modal('show');
	});

	//列表查询事件
	$('#search').click(function(){
		if(($('#shipidnumber').val() == '' && $('#shipname').val() == '') 
				|| ($('#shipidnumber').val() == '' && $('#shipname').val().length < 2)){
			// 搜索条件不为空，或者船名至少输入两个字符才允许搜索
			return;
		}
		$('#tableShip').bootstrapTable(('refresh'));  // 很重要的一步，刷新url！
	});

	//查询中文船名事件
	$('#searchShipname').click(function(){
		if('' == $('#companyid').val()){
			window.wxc.xcConfirm("缺少公司编号，请完善公司信息!", window.wxc.xcConfirm.typeEnum.info);
			return;
		}
		var shipname = $('#checkshipname').val();
		if(shipname != ''){
			$.ajax({
				method: 'post',
				url: basePath() + 'share/getLocalShip.do',
				dataType: "json",
		        contentType: "application/json",
				data: JSON.stringify({
					'shipname' : shipname,
					'sysorg': $('#companyid').val()
				}),
				success: function (data){
					if(data.result == 1){
						$('#shipForm')[0].reset(); // 清空表单数据
						bindShipForm(data.datas);
					} else {
						
					}
				}
			});
		}
	});
	
	//查询船舶识别号事件
	$('#searchShipidnumber').click(function(){
		if('' == $('#companyid').val()){
			window.wxc.xcConfirm("缺少公司编号，请完善公司信息!", window.wxc.xcConfirm.typeEnum.info);
			return;
		}
		var shipidnumber = $('#checkshipidnumber').val();
		if(shipidnumber != ''){
			$.ajax({
				method: 'post',
				url: basePath() + 'share/getLocalShip.do',
				dataType: "json",
		        contentType: "application/json",
				data: JSON.stringify({
					'shipidnumber' : shipidnumber,
					'sysorg': $('[name="companyid"]').val()
				}),
				success: function (data){
					if(data.result == 1){
						$('#shipForm')[0].reset(); // 清空表单数据
						bindShipForm(data.datas);
					} else {
						
					}
				}
			});
		}
	});
	
	$('#addShipModal').click(function(){

		$('#modalShip').modal('hide');

		// 获取字典数据
		bindDict("areacode", "DM_F01_3", "");
		bindDict("markcode", "DM_F05_10", "");
		bindDict("typecode", "DM_F01_6", "");
		bindDict("portcode", "DM_F01_5", "");
		bindDict("flagcode", "DM_F01_15", "");
		bindDict("shiptypecode", "DM_F05_2", "");
		
		$("#flagcode").select2({
			  width: '100%',
			  language: "zh-CN",
		});		
		$("#portcode").select2({
			  language: "zh-CN",
			  width:'100%',
		});		
		
		$("#typecode").select2({
			  language: "zh-CN",
			  width:'100%',
		});		
		
		$("#shiptypecode").select2({
			language: "zh-CN",
			width:'100%',
		});		
		
		$('#shipForm')[0].reset(); // 清空表单数据
		
		$('#modalAddShip').modal('show');
	});
	
	emptyShip();
	$('#addShip').click(function(){
		var row = $('#shipForm').serializeObject();
		
//		$('#tableShip').bootstrapTable('insertRow', {
//			index:$('#tableShip').bootstrapTable('getOptions').totalRows,
//			row:shipData
//		});
		
		var checkErrorStr = '';
		var flag=$('#flagcode').val();
		
		var checkShipStr = ['shipname','shipidnumber','flagcode','portcode','markcode','typecode','areacode','owner','operator'];
//		1.外国籍船舶IMO号必填，验证9位，识别号和登记号可非必填
		if('' != flag && '125' != flag && '384' != flag && '275' != flag){ // 外国籍船舶 
			if($('[name="imo"]').val() == '' || $('[name="imo"]').val().length != 9){
				checkErrorStr += '请输入IMO号,验证9位<br />';
			}
			for(var i = 0; i < checkShipStr.length; i++){
				if($('[name="'+checkShipStr[i]+'"]').val() == ''){
					if(checkShipStr[i] == 'shipidnumber'){
						continue;
					}
					checkErrorStr += $('[name="'+checkShipStr[i]+'"]').attr('placeholder') + '<br />';
				}
			}
//		2.港澳籍船舶：牌簿号必填，船名必填，其他都可非必填
		} else if ('384' == flag || '275' == flag){ // 澳门
			if($('[name="shipname"]').val() == ''){
				checkErrorStr += $('[name="shipname"]').attr('placeholder') + '<br />';
			}
			if($('[name="cardno"]').val() == '' ){
				checkErrorStr += '请输入牌簿号<br />';
			}
		} else {
			for(var i = 0; i < checkShipStr.length; i++){
				if($('[name="'+checkShipStr[i]+'"]').val() == ''){
					checkErrorStr += $('[name="'+checkShipStr[i]+'"]').attr('placeholder') + '<br />';
				}
			}
		}
		
		if(checkErrorStr != ''){
			$.alert({
			    title: '提示!',
			    content: checkErrorStr,
			    confirmButton: '确定'
			});
			return ;
		}

    	if(document.getElementById("ship")) {//js判断元素是否存在
	    	$('#ship').val(row.shipname);
	    	$('#ship').attr('data', JSON.stringify(row));
    	}
    	
    	if(typeof bindShipList=="function"){//js判断方法否存在
    		bindShipList(row);
    	}

		$('#modalShip').modal('hide');

		$('#modalAddShip').modal('hide');
		
		// 将船舶新增到本地库。
		row.syscreatedby = $("#proposerid").val();
		row.syscreatedbyname = $("#proposer").val();
		row.sysorg = $("#companyid").val();
		row.sysorgname = $("#company").val();
		addLocalShip(row);
	});
});


function emptyShip(){
	if($('#TableShip').find('tbody').find("tr").length == 0){
		var htmlStr = '	<tr id = "empty">'+
					'			<td colspan="8" style="font-size:14px; color:#810202;">	'+
					'				单击“添加船舶”新增船舶信息！	'+
					'			</td>	'+
					'		</tr>	';
		
		$('#TableShip').append(htmlStr);
	}
}

function initShipTable(currentPage){
	$('#tableShip').bootstrapTable({
		method: 'post',
	    url: basePath() + 'business/getshiplist.do',
	    pagination: true, //分页
	    dataType: "json",
        contentType: "application/json",
        pageList: [10, 20, 50, 100],  //可供选择的每页的行数（*）
        striped: true,      //是否显示行间隔色
        sidePagination: "server",
        ////查询参数,每次调用是会带上这个参数，可自定义
        queryParams:function(params) {
        	var param = {};
        	param['currentPage'] = params.offset / params.limit + 1;
        	param['pageSize'] = params.limit;
        	if($('#shipidnumber').val() != '')
        		param['SHIP_ID'] = $('#shipidnumber').val();
        	if($('#shipname').val() != '' && $('#shipname').val().length >= 2)
        		param['SHIP_NAME_CN'] = $('#shipname').val();        		
        	if($('#shipidnumber').val() == '' && $('#shipname').val() == '')
        		return ;  
        	
            return param;
        },
	    columns: [{
            field : 'number',  
            title : '序号',  
            align : 'center',
            width : '80px',
            formatter : function(value, row, index) {  
// 		                return index + 1;  
                var page = $('#tableShip').bootstrapTable("getPage");  
                return page.pageSize * (page.pageNumber - 1) + index + 1;  
            }  
        }, {
            align : 'center',
	        field: 'shipidnumber',
	        title: '船舶识别号'
	    }, {
            align : 'center',
	        field: 'shipname',
	        title: '船舶中文名称'
	    }, {
            align : 'center',
	        field: 'shipnameen',
	        title: '船舶英文名称'
	    }, {
            field: 'operate',
            title: '选择',
            align: 'center',
            events: operateEvents,
            formatter: operateFormatter
        } ]
	});
}

	function operateFormatter(value, row, index) {
	    return [
//	        '<button type="button" class="Edit btn btn-warning  btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-edit"></span>编辑</button>',
	        '<button type="button" class="Ship btn btn-success  btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-chevron-left"></span><span class="glyphicon glyphicon-chevron-left"></span>选择</button>'
	    ].join('');
	}
	
	
	
	function check(row){
		var param = {
			"SHIP_REG_NO": row.regno,
			"SHIP_ID" : row.shipidnumber,
			"SHIP_NO" : row.initregno
		}
	$.ajax({ 
		url: projectPath + "share/check.do",
		dataType: "json",
		type : "post",
		data: JSON.stringify(param) ,
		contentType: "application/json",
		success: function(data){
			var verifyresult = 1;
			for(var i=0;i<data.length;i++){
				if(data[i].verifyresultcode < 0){
					verifyresult = -1;
					break ;
				}else
					verifyresult *= data[i].verifyresultcode;
			}
			
			row.verifyresult = verifyresult;
			row.verify = data;
			var src;
			if(row.verifyresult > 0)
				src="../../img/jiaoyan1.png";
			else if(row.verifyresult == 0)
				src="../../img/jiaoyan2.png";
			else
				src="../../img/jiaoyan3.png"
			if((document.getElementById("shipcheckinfo"))){
				$('#ship').attr('data', JSON.stringify(row));
				$("#shipcheckinfo").html('<img src="'+src+'" alt="" style="width:20px;height:20px;" data-toggle="modal" data-target="#modalCheck" onclick="checkInfo('+JSON.stringify(row.verify).replace(/\"/g,"'")+')" title="点击查看详情">');
			}
			else{
				$("#ship"+row.shipidnumber).val(JSON.stringify(row));
				$("#img"+row.shipidnumber).html('<img src="'+src+'" alt="" style="width:20px;height:20px;" data-toggle="modal" data-target="#modalCheck" onclick="checkInfo('+JSON.stringify(row.verify).replace(/\"/g,"'")+')" title="点击查看详情">');
			}
			//$.bootstrapLoading.end();
		},
		error: function (jqXHR, textStatus, errorThrown) {
			//$.bootstrapLoading.end();
			alert("请求出错");
		}
	});
	}
	
	window.operateEvents = {
		    'click .Ship': function (e, value, row, index) {		//列表操作栏【流程定义】
		    	if(document.getElementById("tr_"+row.shipidnumber)){   //元素已存在
		    		window.wxc.xcConfirm("船舶已存在，请重新选择!", window.wxc.xcConfirm.typeEnum.info);
		    		return ;
		    	}
		    	if(document.getElementById("ship")) {//js判断元素是否存在
			    	$('#ship').val(row.shipname);
//			    	row.verifyresult = 4;
			    	$('#ship').attr('data', JSON.stringify(row));
//			    	$("#shipcheckinfo").html('<img src="../../img/loading.gif" alt="" style="width:20px;height:20px;" onclick="" title="数据校验中">');
//			    	check(row);
		    	}
		    	
		    	if(typeof bindShipList=="function"){//js判断方法否存在
		    		//$.bootstrapLoading.start({ loadingTips: "船舶数据校验中，请稍候..." });
//		    		row.verifyresult = 4; //正在校验中
		    		bindShipList(row);
		    		if(document.getElementById("empty")) {//js判断元素是否存在
		    			$("#empty").remove();
		    		}
//		    		check(row);  //进行共享库校验
		    		
		    	}

				$('#modalShip').modal('hide');
		    }
		 };
	
	function addLocalShip(data){
		$.ajax({ 
			url: projectPath + "share/addLocalShip.do",
			type : "post",
			data: JSON.stringify(data),
			dataType: "json",
			contentType: "application/json",
			success: function(data){
				if(data.result != 1){
					console.log(data.info);
				}
			},
			error: function(XMLHttpRequest, textStatus){
				console.log(XMLHttpRequest.responseText);
			}
		});
	}
	
	function bindShipForm(jsonBusiness){
		for (var d in jsonBusiness) {// 遍历json对象的每个key/value对,p为key
			if (d == 'builddate') {
				
			$('[name="' + d + '"]').val(formatDate(jsonBusiness[d], 'yyyy-mm-dd'));
			
			} else if (d == 'areacode' || d == 'markcode' || d == 'typecode'
					|| d == 'portcode' || d == 'flagcode' || d == 'shiptypecode') {
				
				$("#" + d).val(jsonBusiness[d]).trigger('change');
				
			} else {
				$('[name="' + d + '"]').val(jsonBusiness[d] == 0 ? null : jsonBusiness[d]);
			}
		}
	}
	
//	window.operateEvents = {
//	    'click .Ship': function (e, value, row, index) {		//列表操作栏【流程定义】
//	    	if(document.getElementById("ship")) {//js判断元素是否存在
//		    	$('#ship').val(row.shipname);
//		    	$('#ship').attr('data', JSON.stringify(row));
//	    	}
//	    	
//	    	if(typeof bindShipList=="function"){//js判断方法否存在
//	    		bindShipList(row);
//	    	}
//
//			$('#modalShip').modal('hide');
//	    }
//	 };
